<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Happy dong
 * Created Time: 2019-07-31 20:12
 *
 * Version: 2.0
 */

namespace App\Modules\Inventory\Repositories;


use App\Models\GoodsOrder;
use App\Modules\Inventory\Criterias\GetOrderDetailBillListByOrderIdsCriteria;
use Flower\Core\Repository\Eloquent\BaseRepository;

class GoodsOrderRepository extends BaseRepository
{
	public function model()
	{
		return GoodsOrder::class;
	}

	/**
	 * 今天商品销售总价 店铺或者理发师
	 * @param $storeId
	 * @param int $userId
	 * @return mixed
	 */
	public function getGoodsSaleAmount($storeId,$userId=0,$dateList=null){
		$where = empty($userId) ? ['store_id'=>$storeId] : [
			'store_id' =>$storeId,
			'user_id'  =>$userId
		];
		$model = $this->model
			->where($where);
		isset($dateList) ?
			$model->whereDate('created_at','<=',$dateList['start_date'])
				->whereDate('created_at','>=',$dateList['end_date'])
				:
			$model->whereDate('created_at',date('Y-m-d',time()));
		return $model->sum('real_price');
	}

	/**
	 * 今天商品销售总单数 店铺或者理发师
	 * @param $storeId
	 * @param int $userId
	 * @return mixed
	 */
	public function getGoodsSaleCount($storeId,$userId=0){
		$where = empty($userId) ? ['store_id'=>$storeId] : [
			'store_id' =>$storeId,
			'user_id'  =>$userId
		];
		return $this->model->where($where)->whereDate('created_at',date('Y-m-d'))->count();
	}



    /**
     * 创建商品销售订单
     * @param $store_id
     * @param $user_id
     * @param $goods_id
     * @param $real_price
     * @param $count
     * @param $buying_price
     * @param $market_price
     * @param $payment
     * @param $royalty
     * @param $remark
     * @return mixed
     */
	public function createGoodsOrder($store_id,$user_id,$goods_id,$real_price,$count,$buying_sum,$market_sum,$payment,$royalty,$remark)
    {
        $data = [
            'store_id' => $store_id,
            'user_id' => $user_id,
            'goods_id' => $goods_id,
            'real_price' => $real_price,
            'count' => $count,
            'buying_price' => 0,
            'market_price' => 0,
            'buying_sum' => $buying_sum,
            'market_sum' => $market_sum,
            'payment' => $payment,
            'royalty' => $royalty,
            'remark' => $remark,
        ];

        return $this->create($data);
    }


    public function getStoreGoodsAmount($date){
		$goodAmountList = $this->model->selectRaw('store_id,sum(market_sum) as amount,sum(buying_sum) as buying_sum')->groupBy('store_id')->whereDate('created_at',$date)->get()->toArray();
	    return empty($goodAmountList) ? [] : array_column($goodAmountList, null, 'store_id');
    }
    /**
     * 获取某日销售额
     * @param $user_id
     * @param $date
     * @return mixed
     */
    public function getBarberDateGoodsOrderAmount($user_id,$store_id,$date)
    {
        return $this->model->where('user_id',$user_id)
            ->where('store_id',$store_id)
            ->whereRaw('TO_DAYS( "' . $date . '" ) - TO_DAYS(created_at) >= 0')
            ->whereRaw('TO_DAYS( "' . $date . '" ) - TO_DAYS(created_at) < 1')
            ->get()
            ->sum('price');
    }


    public function getAmountRankListByBarberId($storeId,$startDate,$endDate){
        return $this->model
            ->selectRaw('sum(real_price - buying_sum - royalty) as counts,user_id')
            ->with(['user'=>function($v){
                $v->select(['id','nick','portrait'])->with('picture:id,image');
            }])
            ->whereRaw('store_id ="' . $storeId . '" and date(created_at) <= "' .$startDate. '" and date(created_at) >="' . $endDate . '"   and status=1 group by user_id order by counts desc')
            ->get();
    }

    /**
     * 今天商品销售总价 店铺或者理发师
     * @param $storeId
     * @param int $userId
     * @return mixed
     */
    public function getGoodsSaleAmountDate($user_id,$store_id,$end_day){
        return $this->model->where('user_id',$user_id)
            ->whereDate('created_at','>=',$end_day)
            ->where('store_id',$store_id)
            ->get()
            ->sum('market_sum');
    }

    /**
     * 获取商品订单分析
     * @param $store_id
     * @param $user_id
     * @param $end_day
     * @return mixed
     */
    public function getGoodsOrderAnalysis($store_id,$user_id,$end_day)
    {
        $select = [
            'hx_picture.image',
            'hx_goods.name as title',
            'hx_goods_order.created_at',
            'hx_goods_order.real_price as amount',
            'hx_goods_order.royalty as profit'
        ];

        $select = implode($select, ',');
        return $this->model
            ->selectRaw($select)
            ->leftJoin('goods', 'goods_order.goods_id', 'goods.id')
            ->leftJoin('picture', 'goods_order.goods_id', 'picture.id')
            ->where('user_id', $user_id)
            ->whereDate('goods_order.created_at', '>=', $end_day)
            ->where('goods_order.store_id', $store_id);
    }

    public function getGoodsSalesList($dateList,$storeId,$pageSize){
    	return $this->model
		    ->with(['items'=>function($v){
		    	$v->with(['goods'=>function($v){
				    $v->select(['id','small_name','image'])->with('image:id,image');
			    }]);
		    }])
		    ->where('store_id','=',$storeId)
		    ->whereDate('created_at','>=',$dateList['end_date'])
		    ->whereDate('created_at','<=',$dateList['start_date'])
		    ->paginate($pageSize, ['*'], 'paginate');

    }

    public function getGoodsCost($dateList,$storeId){
    	return $this->model->where(['store_id'=>$storeId])
		    ->whereDate('created_at','>=',$dateList['end_date'])
		    ->whereDate('created_at','<=',$dateList['start_date'])
		    ->sum('buying_sum');
    }

	/**
	 * 商品销售利润
	 * @param $dateList
	 * @param $storeId
	 * @return mixed
	 */
    public function getGoodsProfit($dateList,$storeId,$userId=0){
    	$where['store_id'] = $storeId;
    	empty($userId) ? : $where['user_id'] = $userId;
	    $data = $this->model
		    ->selectRaw( 'sum(real_price - buying_sum-royalty) as profit')
		    ->where($where)
		    ->whereDate('created_at','>=',$dateList['end_date'])
		    ->whereDate('created_at','<=',$dateList['start_date'])
		    ->first();
	    return isset($data->profit) ? $data->profit : 0;
    }

	/**
	 * 获取订单列表
	 * @param $orderIds
	 * @return mixed
	 * @throws \Flower\Core\Repository\Exceptions\RepositoryException
	 */
	public function getOrderListByIds($orderIds){
		return $this->pushCriteria(new GetOrderDetailBillListByOrderIdsCriteria($orderIds))->get()->toArray();
	}

	/**
	 * 获取订单详情
	 * @param $orderIds
	 * @return mixed
	 * @throws \Flower\Core\Repository\Exceptions\RepositoryException
	 */
	public function getOrderDetailInfo($orderIds){
		return $this->pushCriteria(new GetOrderDetailBillListByOrderIdsCriteria($orderIds))->first();
	}
}
